package com.baosu.controller.back;

import com.baosu.domain.ImgSha1;
import com.baosu.domain.Result;
import com.baosu.service.ImgSha1Service;
import com.baosu.util.SHA1Utils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@RestController
@Api(tags = "上传下载接口")
public class FileController {

    @Autowired
    private ImgSha1Service imgSha1Service;

    @Value("${upload.path}")
    private String basePath;

    @PostMapping("/upload")
    @ApiOperation(value = "上传")
    public Result upload(@RequestParam("file") MultipartFile file) throws IOException {

        InputStream inputStream = file.getInputStream();

        String sha1 = SHA1Utils.checksumToString(inputStream);
        System.out.println("sha1 = " + sha1);
        ImgSha1 imgSha1 = imgSha1Service.getBySha1(sha1);
        if (imgSha1 != null) {
            return Result.ok(imgSha1.getImg()).message("文件上传成功");
        }

        //原始文件名
        String originalFilename = file.getOriginalFilename();//abc.jpg
        //截取文件后缀
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));

        //使用UUID重新生成文件名，防止文件名称重复造成文件覆盖
        String fileName = UUID.randomUUID().toString() + suffix;//dfsdfdfd.jpg

        //创建一个目录对象
        File dir = new File(basePath);
        //判断当前目录是否存在
        if (!dir.exists()) {
            //目录不存在，需要创建
            dir.mkdirs();
        }

        try {
            //将临时文件转存到指定位置
            file.transferTo(new File(basePath + fileName));
            imgSha1Service.save(new ImgSha1(fileName, sha1));
        } catch (IOException e) {
            e.printStackTrace();
            return Result.fail(null).message("文件上传失败");
        }
        return Result.ok(fileName).message("文件上传成功");
    }


    @GetMapping("/download/{name}")
    @ApiOperation(value = "下载")
    public Result download(@PathVariable String name, HttpServletResponse response){
        try {
            //输入流，通过输入流读取文件内容
            FileInputStream fileInputStream = new FileInputStream(new File(basePath + name));
            //输出流，通过输出流将文件写回浏览器
            ServletOutputStream outputStream = response.getOutputStream();
            //设置响应文件类型
            response.setContentType("image/jpeg");

            int len = 0;
            byte[] bytes = new byte[1024];
            while ((len = fileInputStream.read(bytes)) != -1){
                outputStream.write(bytes,0,len);
                outputStream.flush();
            }
            //关闭资源
            outputStream.close();
            fileInputStream.close();
            return Result.ok(null);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail(null).message("文件获取失败");
        }
    }

}
